package com.yupi.springbootinit.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DeleteRequest;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.model.dto.supportgrindingrecord.SupportGrindingRecordAddRequest;
import com.yupi.springbootinit.model.dto.supportgrindingrecord.SupportGrindingRecordQueryRequest;
import com.yupi.springbootinit.model.dto.supportgrindingrecord.SupportGrindingRecordUpdateRequest;
import com.yupi.springbootinit.model.entity.SupportGrindingRecord;
import com.yupi.springbootinit.model.vo.SupportGrindingRecordVO;
import com.yupi.springbootinit.service.ProcessSheetService;
import com.yupi.springbootinit.service.SupportGrindingRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Map;

/**
 * 去支撑打磨记录接口
 */
@RestController
@RequestMapping("/supportGrindingRecord")
@Slf4j
public class SupportGrindingRecordController {

    @Resource
    private SupportGrindingRecordService supportGrindingRecordService;
    @Resource
    private ProcessSheetService processSheetService;

    // region 增删改查

    /**
     * 创建去支撑打磨记录
     *
     * @param addRequest 创建请求
     * @param request    HttpServletRequest
     * @return 新记录ID
     */
    @PostMapping("/add")
    public BaseResponse<Long> addRecord(@RequestBody SupportGrindingRecordAddRequest addRequest,
                                        HttpServletRequest request) {
        if (addRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SupportGrindingRecord record = new SupportGrindingRecord();
        BeanUtils.copyProperties(addRequest, record);

        // 数据校验
        supportGrindingRecordService.validRecord(record, true);

        // 写入数据库
        boolean result = supportGrindingRecordService.save(record);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        // 返回新记录ID
        long newRecordId = record.getId();
        return ResultUtils.success(newRecordId);
    }

    /**
     * 删除去支撑打磨记录
     *
     * @param deleteRequest 删除请求
     * @param request       HttpServletRequest
     * @return 是否成功
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteRecord(@RequestBody DeleteRequest deleteRequest,
                                              HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();

        // 判断是否存在
        SupportGrindingRecord oldRecord = supportGrindingRecordService.getById(id);
        ThrowUtils.throwIf(oldRecord == null, ErrorCode.NOT_FOUND_ERROR);

        // 操作数据库（软删除）
        boolean result = supportGrindingRecordService.removeById(id);
        return ResultUtils.success(result);
    }

    /**
     * 更新去支撑打磨记录（仅管理员）
     *
     * @param updateRequest 更新请求
     * @param request       HttpServletRequest
     * @return 是否成功
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateRecord(@RequestBody SupportGrindingRecordUpdateRequest updateRequest,
                                              HttpServletRequest request) {
        if (updateRequest == null || updateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        SupportGrindingRecord record = new SupportGrindingRecord();
        BeanUtils.copyProperties(updateRequest, record);

        // 数据校验
        supportGrindingRecordService.validRecord(record, false);

        // 判断是否存在
        long id = updateRequest.getId();
        SupportGrindingRecord oldRecord = supportGrindingRecordService.getById(id);
        ThrowUtils.throwIf(oldRecord == null, ErrorCode.NOT_FOUND_ERROR);

        // 操作数据库
        boolean result = supportGrindingRecordService.updateById(record);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取去支撑打磨记录（封装类）
     *
     * @param id      记录ID
     * @param request HttpServletRequest
     * @return VO对象
     */
    @GetMapping("/get/vo")
    public BaseResponse<SupportGrindingRecordVO> getRecordVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SupportGrindingRecord record = supportGrindingRecordService.getById(id);
        if (record == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(supportGrindingRecordService.getRecordVO(record, request));
    }

    /**
     * 分页获取去支撑打磨记录列表（仅管理员）
     *
     * @param queryRequest 查询请求
     * @param request      HttpServletRequest
     * @return 分页数据
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<SupportGrindingRecord>> listRecordByPage(@RequestBody SupportGrindingRecordQueryRequest queryRequest,
                                                                      HttpServletRequest request) {
        long current = queryRequest.getCurrent();
        long size = queryRequest.getPageSize();
        Page<SupportGrindingRecord> recordPage = supportGrindingRecordService.page(
                new Page<>(current, size),
                supportGrindingRecordService.getQueryWrapper(queryRequest)
        );
        return ResultUtils.success(recordPage);
    }

    /**
     * 分页获取去支撑打磨记录列表（封装类）
     *
     * @param queryRequest 查询请求
     * @param request      HttpServletRequest
     * @return 分页VO数据
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SupportGrindingRecordVO>> listRecordVOByPage(@RequestBody SupportGrindingRecordQueryRequest queryRequest,
                                                                          HttpServletRequest request) {
        long current = queryRequest.getCurrent();
        long size = queryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<SupportGrindingRecord> recordPage = supportGrindingRecordService.page(
                new Page<>(current, size),
                supportGrindingRecordService.getQueryWrapper(queryRequest)
        );
        return ResultUtils.success(supportGrindingRecordService.getRecordVOPage(recordPage, request));
    }

    // endregion
    /**
     * 根据产品名称查询工艺单号（用于新建时自动填充）
     */
    @GetMapping("/query-process-sheet-by-product")
    public BaseResponse<Map<String, Object>> queryProcessSheetByProduct(@RequestParam String productName) {
        if (StringUtils.isBlank(productName)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "产品名称不能为空");
        }
        return ResultUtils.success(processSheetService.queryProcessSheetByProductName(productName));
    }
}